/**
 * 路由
 */

var sessionApis = require('session.js'), roomApis = require('room.js');


// 包装一些公共操作，如检测登录，输出处理结果等
function _wrap(fn, isPolling, onClose) {
	return function(req, res) {
		var self = this;
		
		var player = sessionApis.get(req.cookies['name'] || '', req.cookies['password'] || '');
		// 登录检查
		if (!player) {
			res.json({
				type : 'error',
				status : 0,
				message : '请先登录'
			});
		}
		
		// 记录轮询开始时间及计时器编号
		var startTime = +new Date, timerId;
		
		// 连接异常断开时，停止轮询
		req.on('close', function() {
			timerId && clearTimeout(timerId);
			console.log(player.name + ' disconnected');
			onClose && onClose.call(this, player);
		});
		
		var exec = function() {
			// 更新玩家在线时间
			player.timestamp = +new Date;
			
			var result;
			
			try {
				result = fn.call(self, req, res, player);
			} catch(e) {
				res.json({
					type : 'error',
					status : 1,
					message : typeof e === 'string' ? e : e.message
				});
			}
			
			if (result) {
				res.json(result);
			} else {
				if (isPolling && new Date - startTime < 40000) {
					timerId = setTimeout(exec, 1000);
				} else {
					res.end();
				}
			}
		};
		
		exec();
	};
}


exports.player = {
	/**
	 * 玩家登录
	 */
	login : function(req, res) {
		var player;
		try {
			player = sessionApis.create(req.body.nickname);
		} catch (e) {
			res.json(e);
		}
		
		res.json(player);
	},
	
	/**
	 * 根据Cookie中的用户名和密码查找玩家
	 */
	get : function(req, res) {
		var player = sessionApis.get(req.cookies.name || '');
		if (player && player.password == req.cookies.password) {
			res.json(player);
		} else {
			res.end();
		}
	}
};


exports.room = {
	/**
	 * 房间列表
	 */
	list : _wrap(function(req, res) {
		return roomApis.list(req.params.timestamp);
	}, true),

	/**
	 * 创建房间并进入
	 */
	create : _wrap(function(req, res, player) {
		return roomApis.create(player);
	}),
	
	/**
	 * 进入房间
	 */
	enter : _wrap(function(req, res, player) {
		return roomApis.enter(req.body.roomId, player);
	}),
	
	/**
	 * 离开房间
	 */
	exit : _wrap(function(req, res, player) {
		return roomApis.exit(player);
	}),
	
	/**
	 * 设置准备状态为已准备
	 */
	setReady : _wrap(function(req, res, player) {
		return roomApis.setReady(player, true);
	}),
	
	/**
	 * 取消已准备状态
	 */
	cancelReady : _wrap(function(req, res, player) {
		return roomApis.setReady(player, false);
	}),
	
	/**
	 * 开始游戏
	 */
	startGame : _wrap(function(req, res, player) {
		return roomApis.startGame(player);
	}),
	
	/**
	 * 出牌
	 */
	submitPokers : _wrap(function(req, res, player) {
		return roomApis.submitPokers( player, req.body.value ? req.body.value.split(',').map(function(n) {
			return Number(n);
		}) : null );
	}),
	
	/**
	 * 获取房间最新状态
	 */
	query : _wrap(function(req, res, player) {
		var room = roomApis.query(req.params.roomId, req.params.timestamp);
		if (room != null) {
			// 复制一份
			var result = JSON.parse( JSON.stringify(room) );
			if (result.started) {
				// 隐藏其他玩家的牌，仅返回牌数
				for (var i = 0, tempPlayer; tempPlayer = result.players[i]; i++) {
					if (tempPlayer.name !== player.name && tempPlayer.pokers) {
						tempPlayer.pokers = tempPlayer.pokers.length;
					}
				}
			}
			
			return result;
		}
	}, true, function(player) {
		var room = roomApis.list().list[player.location];
		// 断线时强制退出
		if (room) {
			room.exit(player.name, true);
		}
	})
};